package com.canbot.u05.activity.training;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.adapter.training.TrainingListViewAdapter;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.TrainingEditTextDialog;
import com.canbot.u05.view.TrainingHostDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 培训主持模式列表的界面----包括添加任务,删除任务
 */
public class TrainingListViewActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private static final String TAG = "TrainingListViewActivity";

        public  List<String> mListData = new ArrayList<>();

        private ListView listView;

        private TrainingListViewAdapter list_ada;

        public int currentPosition;

        private Dialog dialogLoading;

        private TrainingEditTextDialog editTextDialog;

        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        if (mListData == null) {
                                ToastTools.newInstance(TrainingListViewActivity.this).showText(getString(R.string.no_current_task));
                        }
                        else {
                                updateView();
                        }
                }
        };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.act_training_host_list);
                initView();

                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.TRAINING_DIR + "pxzcszdr_pxzc_u05_001.wav");
                MsgSendUtils.sendStringMsg(MsgType.ACTION, "14009");
                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "12");
        }


        private void initView() {
                listView = (ListView) findViewById(R.id.listView);

                findViewById(R.id.bt_back).setOnClickListener(this);
                findViewById(R.id.bt_add).setOnClickListener(this);

        }


        @Override
        protected void onResume() {
                super.onResume();
                initData();
        }

        private void updateView() {
                list_ada = new TrainingListViewAdapter(this, mListData);
                listView.setAdapter(list_ada);
                list_ada.setListner(new TrainingListViewAdapter.AdapterOnclickListner() {
                        @Override
                        public void onclick(int id) {
                                showTaskDialog(id);
                        }

                        @Override
                        public void showPopuwindow(int position) {
                                currentPosition = position;
                        }

                        @Override
                        public void doTask(int id) {
                                //跳转到步骤界面
                                startActivity(new Intent(TrainingListViewActivity.this,StaffTrainingActivity.class)
                                        .putExtra("taskName",mListData.get(id)));

                        }
                });
        }


        /**
         * 初始化数据
         */
        private void initData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(TrainingListViewActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", 0);
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST+ ":7755/" + "trainPresided", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                final String msg;

                                if (strMsgBean.getRc() != 0) {
                                        msg = strMsgBean.getMsg();
                                }else {
                                        msg = "数据加载成功";
                                }
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                if (strMsgBean.getRc() == 0) {
                                                        dialogLoading.dismiss();
                                                        ToastTools.newInstance(TrainingListViewActivity.this).showText(msg);
                                                        mListData = JSON.parseArray(strMsgBean.getResult().toString(), String.class);
                                                        mHandler.sendEmptyMessage(0);
                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG, "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                ToastTools.newInstance(TrainingListViewActivity.this).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });

        }

        //添加任务对话框
        public void showTaskDialog(int id) {
                final TrainingHostDialog dialog = new TrainingHostDialog(this, id);
                dialog.setListner(new TrainingHostDialog.ModeDialogOclickListner() {
                        @Override
                        public void onClick(int id) {
                                switch (id) {
                                        case R.id.dialog_cancel:
                                                dialog.dismiss();
                                                break;
                                        case R.id.dialog_sure://删除
                                                deleteTask(mListData.get(currentPosition));
                                                break;
                                        case R.id.dialog_rename_cancel:
                                                dialog.dismiss();
                                                break;
                                        case R.id.dialog_rename_sure://换名
                                                String etName = dialog.getEtName().trim();
                                                if (TextUtils.isEmpty(etName)) {
                                                        dialog.setEtName(TrainingListViewActivity.this.getString(R.string.please_first_named));
                                                        return;
                                                }
                                                for(String taskName:mListData){
                                                        if (etName.equals(taskName)) {
                                                                editTextDialog = new TrainingEditTextDialog(TrainingListViewActivity.this, 3);
                                                                editTextDialog.setOnPositiveListener(new View.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(View view) {
                                                                                editTextDialog.dismiss();
                                                                        }
                                                                });
                                                                editTextDialog.show();
                                                                return;
                                                        }
                                                }
                                                renameTask(mListData.get(currentPosition),etName);
                                                break;

                                }
                        }
                });
                dialog.show();
                setDialogWindowAttr(dialog, this);
        }

        @Override
        protected void onRestart() {
                super.onRestart();
        }

        /**
         * 删除任务
         */
        private void deleteTask(final String name) {

                dialogLoading = LoadingDialogUtils.createLoadingDialog(TrainingListViewActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", 4);
                hasMap.put("taskName",name );
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST+ ":7755/" + "trainPresided", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                final String msg;

                                if (strMsgBean.getRc() != 0) {
                                        msg = strMsgBean.getMsg();
                                }else {
                                        msg = TrainingListViewActivity.this.getString(R.string.deleted_successfully);
                                }
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {

                                                if (strMsgBean.getRc() == 0) {
                                                        ToastTools.newInstance(TrainingListViewActivity.this).showText(msg);
                                                        mListData.remove(name);
                                                        list_ada.notifyDataSetChanged();
                                                        dialogLoading.dismiss();

                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("StaffTrainingActivity", "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                ToastTools.newInstance(TrainingListViewActivity.this).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });
        }

        /**
         * 重命名任务
         *
         * @param etName
         */
        private void renameTask(String oldName, final String etName) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(TrainingListViewActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", 5);
                hasMap.put("oldName",oldName);
                hasMap.put("newName",etName);
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST+ ":7755/" + "trainPresided", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                final String msg;

                                if (strMsgBean.getRc() != 0) {
                                        msg = strMsgBean.getMsg();
                                }else {
                                        msg = TrainingListViewActivity.this.getString(R.string.rename_success);
                                }
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {

                                                if (strMsgBean.getRc() == 0) {
                                                        dialogLoading.dismiss();
                                                        mListData.set(currentPosition,etName);
                                                        list_ada.notifyDataSetChanged();
                                                        ToastTools.newInstance(TrainingListViewActivity.this).showText(msg);
                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("StaffTrainingActivity", "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                ToastTools.newInstance(TrainingListViewActivity.this).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });

        }

        //设置对话框显示
        public static void setDialogWindowAttr(Dialog dlg, Context ctx) {
                Window window = dlg.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = Gravity.CENTER;
                lp.width = (int) ctx.getResources().getDimension(R.dimen.x540);//宽高可设置具体大小
                lp.height = (int) ctx.getResources().getDimension(R.dimen.x278);
                dlg.getWindow().setAttributes(lp);
        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.bt_back:
                                finish();
                                break;
                        case R.id.bt_add:
                                startActivity(new Intent(TrainingListViewActivity.this, StaffTrainingActivity.class)
                                        .putExtra("stepList", JSON.toJSONString(mListData)));
                                break;
                }

        }
}